<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import Sidebar from '../components/Sidebar.vue';

type ReportTask = {
  id: number;
  name: string;
  dataSource: string;
  status: string;
  content: string | null;
  duration: string;
  created: string;
};

type DataSource = {
  id: number;
  name: string;
}

const router = useRouter();
const reportTasks = ref<ReportTask[]>([]);
const isLoading = ref(true);
const isModalOpen = ref(false);
const dataSources = ref<DataSource[]>([]);
const newReport = reactive({ name: '', dataSourceId: '' });

const fetchReports = async () => {
  isLoading.value = true;
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/reports', {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    if (!response.ok) throw new Error('Failed to fetch reports.');
    reportTasks.value = await response.json();
  } catch (error) {
    console.error(error);
    // 可在此处添加用户友好的错误提示
  } finally {
    isLoading.value = false;
  }
};

const fetchDataSources = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/datasources', {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    if (!response.ok) throw new Error('Failed to fetch data sources.');
    dataSources.value = await response.json();
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  fetchReports();
  fetchDataSources();
});

const refreshReport = async (id: number) => {
  const task = reportTasks.value.find(t => t.id === id);
  if (task) {
    task.status = 'Processing';
  }

  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/reports/${id}/refresh`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}` } });
    if (!response.ok) throw new Error('Failed to start refresh.');
    
    // 等待一段时间后刷新列表以获取最新状态
    setTimeout(() => {
      fetchReports();
    }, 4000); // 假设AI分析需要一些时间

  } catch (error) {
    console.error('Failed to refresh report:', error);
    if (task) {
      task.status = 'Failed'; // 更新UI以反映失败状态
    }
  }
};

const openCreateModal = () => {
  newReport.name = '';
  newReport.dataSourceId = '';
  isModalOpen.value = true;
};

const closeModal = () => {
  isModalOpen.value = false;
};

const createReport = async () => {
  if (!newReport.name || !newReport.dataSourceId) {
    alert('Please fill in all fields.');
    return;
  }
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/reports', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(newReport),
    });
    if (!response.ok) throw new Error('Failed to create report.');
    
    closeModal();
    fetchReports(); // 重新加载列表
  } catch (error) {
    console.error('Failed to create report:', error);
    alert('Error creating report.');
  }
};

const goBack = () => {
  router.back();
};

const getStatusClass = (status: string) => {
  switch (status) {
    case 'Completed': return 'bg-green-100 text-green-800';
    case 'Processing': return 'bg-blue-100 text-blue-800 animate-pulse';
    case 'Pending': return 'bg-yellow-100 text-yellow-800';
    case 'Failed': return 'bg-red-100 text-red-800';
    default: return 'bg-gray-100 text-gray-800';
  }
};
</script>

<template>
  <div class="report-page bg-[var(--secondary-color)] min-h-screen">
    <div class="flex h-full grow">
      <!-- 使用统一的侧边栏组件 -->
      <Sidebar />
      
      <!-- 主内容区域 -->
      <main class="ml-72 flex-1 p-8">
        <div class="max-w-7xl mx-auto">
          <header class="flex items-center justify-between mb-8">
            <div class="flex items-center gap-4">
              <button @click="goBack" class="text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
              </button>
              <h1 class="text-3xl font-bold text-[var(--text-primary)]">报表任务</h1>
            </div>
            <button @click="openCreateModal" class="inline-flex items-center justify-center px-4 py-2.5 text-sm font-semibold rounded-lg bg-[var(--primary-color)] text-[var(--text-primary)] hover:bg-opacity-80 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--primary-color)] transition-colors duration-150">
              <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
              创建新报表
            </button>
          </header>

          <div class="bg-white shadow-sm rounded-lg border border-[var(--border-color)] overflow-hidden">
            <div class="overflow-x-auto">
              <table class="min-w-full divide-y divide-[var(--border-color)]">
                <thead class="bg-slate-50">
                  <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase tracking-wider">报表名称</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase tracking-wider">数据源</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase tracking-wider">状态</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase tracking-wider">创建时间</th>
                    <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-[var(--text-secondary)] uppercase tracking-wider">操作</th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-[var(--border-color)]">
                  <tr v-if="isLoading">
                    <td colspan="5" class="text-center py-10 text-[var(--text-secondary)]">加载报表中...</td>
                  </tr>
                  <tr v-else-if="reportTasks.length === 0">
                      <td colspan="5" class="text-center py-10 text-[var(--text-secondary)]">未找到报表任务。</td>
                  </tr>
                  <tr v-for="task in reportTasks" :key="task.id" class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-[var(--text-primary)]">{{ task.name }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">{{ task.dataSource }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm">
                      <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', getStatusClass(task.status)]">
                        {{ task.status }}
                      </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">{{ new Date(task.created).toLocaleString() }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <button @click="refreshReport(task.id)" :disabled="task.status === 'Processing'" class="text-indigo-600 hover:text-indigo-900 disabled:opacity-50 disabled:cursor-not-allowed">
                        刷新
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </main>
    </div>

    <!-- 新建报表模态框 -->
    <div v-if="isModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 m-4">
        <h2 class="text-xl font-bold text-[var(--text-primary)] mb-6">创建新报表</h2>
        <form @submit.prevent="createReport">
          <div class="space-y-4">
            <div>
              <label for="report-name" class="block text-sm font-medium text-[var(--text-secondary)]">报表名称</label>
              <input type="text" id="report-name" v-model="newReport.name" class="mt-1 block w-full rounded-md border-[var(--border-color)] shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm p-2">
            </div>
            <div>
              <label for="data-source" class="block text-sm font-medium text-[var(--text-secondary)]">数据源</label>
              <select id="data-source" v-model="newReport.dataSourceId" class="mt-1 block w-full rounded-md border-[var(--border-color)] shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm p-2">
                <option disabled value="">请选择一个</option>
                <option v-for="ds in dataSources" :key="ds.id" :value="ds.id">{{ ds.name }}</option>
              </select>
            </div>
          </div>
          <div class="mt-6 flex justify-end gap-4">
            <button type="button" @click="closeModal" class="px-4 py-2 text-sm font-medium text-[var(--text-secondary)] bg-white rounded-md border border-[var(--border-color)] hover:bg-gray-50">取消</button>
            <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-md hover:bg-indigo-700">创建</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<style>
.report-page {
  --primary-color: #dce8f3;
  --secondary-color: #f1f2f4;
  --text-primary: #121416;
  --text-secondary: #6a7681;
  --border-color: #dde1e3;
}
</style> 